package com.acmetelecom;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Call {
    private CallEvent start;
    private CallEvent end;
    private int peakSeconds;
    private int offpeakSeconds;

    public Call(CallEvent start, CallEvent end) {
        this.start = start;
        this.end = end;
        this.peakSeconds = 0;
        this.offpeakSeconds = 0;
        calculateDuration();
    }

    private void calculateDuration() {
    	long current = start.time();
    	long next = getNextSwitchPointfor(current);
    	while(end.time() > current) {
			if(next > end.time()) {
				if(offPeak(next))
					peakSeconds += Math.ceil((end.time()-current)/1000);
				else
					offpeakSeconds += Math.ceil((end.time()-current)/1000);
				current = end.time();
			}
			else {
				if(offPeak(next))
					peakSeconds += Math.ceil((next-current)/1000);
				else
					offpeakSeconds += Math.ceil((next-current)/1000);
				current = next;
				next = getNextSwitchPointfor(current);
			}
    	}
		System.out.println("peakSeconds:" + peakSeconds);
		System.out.println("offpeakSeconds:" + offpeakSeconds);
	}

	private long getNextSwitchPointfor(long time) {
		long day = (long) Math.floor(time/24/60/60/1000);
		int hour = (int) Math.floor((time-day*24*60*60*1000)/1000/60/60);
		if(hour < 7)
			return (day*24+7)*60*60*1000;
		else if(hour >= 7 && hour < 19)
			return (day*24+19)*60*60*1000;
		return (day*24+31)*60*60*1000;
	}
	
	public boolean offPeak(long time) {
		long day = (long) Math.floor(time/24/60/60/1000);
		int hour = (int) Math.floor((time-day*24*60*60*1000)/1000/60/60);
        return hour < 7 || hour >= 19;
    }

	public String callee() {
        return start.getCallee();
    }

    public int durationSeconds() {
        return (int) (((end.time() - start.time()) / 1000));
    }

    public String date() {
        return SimpleDateFormat.getInstance().format(new Date(start.time()));
    }

    public Date startTime() {
        return new Date(start.time());
    }

    public Date endTime() {
        return new Date(end.time());
    }

	public int peakDurationSeconds() {
		return this.peakSeconds;
	}

	public int offpeakDurationSeconds() {
		return this.offpeakSeconds;
	}
}
